package net.chasing.androidbaseconfig.util.glide.base;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;

import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import net.chasing.androidbaseconfig.util.glide.ImageLoadUtils;

import java.lang.ref.WeakReference;

public class BitmapRequestListener implements RequestListener<Bitmap> {
    private final WeakReference<Context> mContext;
    private final WeakReference<ImageView> mIv;
    private final int mCorner;
    private final byte mErrorType;
    private boolean isLeftTop = true, isRightTop = true, isLeftBottom = true, isRightBottom = true;

    public BitmapRequestListener(Context context, ImageView iv, byte errorType, int corner) {
        mContext = new WeakReference<>(context);
        mIv = new WeakReference<>(iv);
        mCorner = corner;
        mErrorType = errorType;
    }

    public BitmapRequestListener setCircleCorner(boolean isLeftTop, boolean isRightTop, boolean isLeftBottom, boolean isRightBottom) {
        this.isLeftTop = isLeftTop;
        this.isRightTop = isRightTop;
        this.isLeftBottom = isLeftBottom;
        this.isRightBottom = isRightBottom;
        return this;
    }

    @Override
    public boolean onLoadFailed(GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
        new Handler(Looper.getMainLooper()).post(()-> ImageLoadUtils.loadRoundDefaultPicByErrorType(mContext.get(), mIv.get(), mCorner, mErrorType, isLeftTop, isRightTop, isLeftBottom, isRightBottom));
        return true;
    }

    @Override
    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
        return false;
    }
}
